package com.wanyu.video.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 聚合和分散缓冲区数据
 */
public class ScatteringAndGatheringTest {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(10086);
        
        // 绑定端口
        serverSocketChannel.socket().bind(inetSocketAddress);
        
        // 创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        // 创建客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();

        int messageLength = 8;
        // 进行读取
        while(true){
            int byteRead = 0;
            while(byteRead < messageLength){
                long read = socketChannel.read(byteBuffers);
                byteRead += read;
                System.out.println(" byteRead = " + byteRead);
                Arrays.stream(byteBuffers).map(buffer -> "position = " + buffer.position() + ", limit = " + buffer.limit())
                        .forEach(System.out::println);
            }

            // 反转buffer的坐标
            Arrays.stream(byteBuffers).forEach(ByteBuffer::flip);

            long byteWrite = 0;
            while(byteWrite < messageLength){
                long write = socketChannel.write(byteBuffers);
                byteWrite += write;
            }

            Arrays.stream(byteBuffers).forEach(ByteBuffer::clear);
        }


    }
}
